package com.wufun.overseas.main.activity;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.papa.controller.core.PadKeyEvent;
import com.wufun.overseas.R;
import com.wufun.overseas.joystick.map.BlackListManager;
import com.wufun.overseas.joystick.map.HandShankUtil;
import com.wufun.overseas.joystick.map.KeyMap;
import com.wufun.overseas.joystick.map.KeyMapManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

//GBC设置
public class HandShankGBCActivity extends HandShankBaseActivity implements OnClickListener {

    @Bind(R.id.select)
    Button select;
    @Bind(R.id.start)
    Button start;


    @Bind(R.id.y)
    Button y;
    @Bind(R.id.x)
    Button x;
    @Bind(R.id.ab)
    Button ab;
    @Bind(R.id.b)
    Button b;
    @Bind(R.id.a)
    Button a;


    @Bind(R.id.resetButn)
    Button resetButn;

    @Bind(R.id.titleText)
    TextView titleText;

    //最终数据包
    private Map<String, String> okMap = new HashMap<String, String>();


    //手柄键盘映射
    private Map<String, Integer> KEY_MAP = new HashMap<String, Integer>();

    //手柄键盘映射
    private Map<String, String> GBC_KEY_MAP = new HashMap<String, String>();

    //按钮类映射
    private Map<String, KeyInfo> data;

    private boolean isReset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gbc_key_map);
        ButterKnife.bind(this);

        afterViews();

    }

    @OnClick(R.id.backImage)
    void backImage() {
        finish();
    }

    private List<String> unSetKeyBoradName;
    private List<String> unSetTag;

    private void unSet() {
        unSetKeyBoradName = new ArrayList<String>();
        unSetTag = new ArrayList<String>();
        for (String tag : GBC_KEY_MAP.keySet()) {
            if (okMap.containsValue(tag)) {
                continue;
            }
            unSetTag.add(tag);
        }

        for (String keyBoradName : GBC_KEY_MAP.values()) {
            if (okMap.containsKey(keyBoradName)) {
                continue;
            }
            unSetKeyBoradName.add(keyBoradName);
        }

        Iterator iterator = unSetTag.iterator();
        while (iterator.hasNext()) {
            String tag          = (String) iterator.next();
            String keyBoradName = GBC_KEY_MAP.get(tag);
            if (unSetKeyBoradName.contains(keyBoradName)) {
                iterator.remove();
                unSetKeyBoradName.remove(keyBoradName);
                okMap.put(keyBoradName, tag);
            }
        }

        if (unSetKeyBoradName.size() >= unSetTag.size()) {
            for (int i = 0; i < unSetTag.size(); i++) {
                okMap.put(unSetKeyBoradName.get(i), unSetTag.get(i));


            }
        }
    }

    @OnClick(R.id.okButn)
    void okButn() {

        if (isReset) {
            isReset = false;
            finish();
            return;
        } else {

            if (okMap.size() < 7) {
                //Toast.makeText(this,"按键映射不能为空哦",Toast.LENGTH_SHORT).show();
                //return;
                unSet();
            }
            KeyMapManager.writeToConfigVK(this, KeyMap.EmuMap.GBC, putMap(okMap));

            finish();


        }

    }

    @OnClick(R.id.resetButn)
    void resetButn() {
        reset();
    }

    private Button selectBtn;

    //	@AfterViews
    void afterViews() {

        initMap();
        initBtn();
        initView();

    }

    private void initMap() {
        data = new HashMap<String, KeyInfo>();
        data.put(HandShankUtil.GBC_KEY_START, new KeyInfo(R.id.start, R.drawable.handshank_set_skey_normal, R.drawable.handshank_set_skey_selected, R.drawable.handshank_set_skey_pressed, R.color.handshank_key_set_normal_txt, R.color.handshank_key_set_selected_txt, R.color.handshank_key_set_pressed_txt, R.id.start_tv));
        data.put(HandShankUtil.GBC_KEY_SELECT, new KeyInfo(R.id.select, R.drawable.handshank_set_skey_normal, R.drawable.handshank_set_skey_selected, R.drawable.handshank_set_skey_pressed, R.color.handshank_key_set_normal_txt, R.color.handshank_key_set_selected_txt, R.color.handshank_key_set_pressed_txt, R.id.select_tv));

        data.put(HandShankUtil.GBC_KEY_A, new KeyInfo(R.id.a, R.drawable.handshank_set_key_normal, R.drawable.handshank_set_key_selected, R.drawable.handshank_set_key_pressed, R.color.handshank_key_set_normal_txt, R.color.handshank_key_set_selected_txt, R.color.handshank_key_set_pressed_txt, R.id.a_tv));
        data.put(HandShankUtil.GBC_KEY_B, new KeyInfo(R.id.b, R.drawable.handshank_set_key_normal, R.drawable.handshank_set_key_selected, R.drawable.handshank_set_key_pressed, R.color.handshank_key_set_normal_txt, R.color.handshank_key_set_selected_txt, R.color.handshank_key_set_pressed_txt, R.id.b_tv));
        data.put(HandShankUtil.GBC_KEY_TURBO_A, new KeyInfo(R.id.x, R.drawable.handshank_set_key_normal, R.drawable.handshank_set_key_selected, R.drawable.handshank_set_key_pressed, R.color.handshank_key_set_normal_txt, R.color.handshank_key_set_selected_txt, R.color.handshank_key_set_pressed_txt, R.id.x_tv));
        data.put(HandShankUtil.GBC_KEY_TURBO_B, new KeyInfo(R.id.y, R.drawable.handshank_set_key_normal, R.drawable.handshank_set_key_selected, R.drawable.handshank_set_key_pressed, R.color.handshank_key_set_normal_txt, R.color.handshank_key_set_selected_txt, R.color.handshank_key_set_pressed_txt, R.id.y_tv));

        data.put(HandShankUtil.GBC_KEY_AB, new KeyInfo(R.id.ab, R.drawable.handshank_set_key_normal, R.drawable.handshank_set_key_selected, R.drawable.handshank_set_key_pressed, R.color.handshank_key_set_normal_txt, R.color.handshank_key_set_selected_txt, R.color.handshank_key_set_pressed_txt, R.id.r1_tv));

        initMapData();
    }

    private void initBtn() {
        titleText.setText(getString(R.string.gamepad_gbc_settings));
        select.setTag("GBC_KEY_SELECT");
        start.setTag("GBC_KEY_START");
        select.setText(getString(R.string.gamepad_key_select));
        start.setText(getString(R.string.gamepad_key_start));
        select.setOnClickListener(this);
        start.setOnClickListener(this);


        y.setOnClickListener(this);

        x.setOnClickListener(this);

        ab.setOnClickListener(this);

        b.setOnClickListener(this);

        a.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        String tag = (String) view.getTag();

        //检查这个按钮是不是在已经设置完毕的map里
        if (!okMap.containsValue(tag)) {//不在已经设置的map里
            //已经有设置过的selectBrn
            if (selectBtn != null) {
                //如果是相同的按钮，不做处理
                if (tag.equals(selectBtn.getTag())) {
                    return;
                }
                //如果不是相同的按钮，取出select上的keyinfo，该对象包含按钮的文字背景信息
                KeyInfo keyInfo = data.get(selectBtn.getTag());
                //将按钮的背景设置为未点击
                selectBtn.setBackgroundResource(keyInfo.normal_drawable);
                //如果按钮文字可设置
                if (keyInfo.normal_txt_color != 0) {
                    //将按钮文字设为未点击
                    selectBtn.setTextColor(getResources().getColor(R.color.handshank_key_set_normal_txt));
                }
            }
            //给select赋新值，新值为当前点击的button
            selectBtn = (Button) view;
            //取出btn上的tag，获取按钮信息keyInfo对像
            KeyInfo keyInfo = data.get(selectBtn.getTag());
            //设置按钮的背景及文字
            selectBtn.setBackgroundResource(keyInfo.select_drawable);
            if (keyInfo.normal_txt_color != 0) {
                selectBtn.setTextColor(getResources().getColor(R.color.handshank_key_set_selected_txt));
            }

        }


    }

    private void revertBtn() {

        Set      set = data.entrySet();
        Iterator i   = set.iterator();
        while (i.hasNext()) {
            Map.Entry<String, KeyInfo> entry1 = (Map.Entry<String, KeyInfo>) i.next();
            String                     key    = entry1.getKey();
            KeyInfo                    info   = data.get(key);
            //取出当前所有的按钮并且判断信息
            //如果这个button已被加入okMap

            if (okMap.containsValue(key)) {
                //取出这个button，背景文字设成被选中
                Button button = (Button) findViewById(info.id);

                if (info.normal_txt_color != 0) {
                    button.setTextColor(getResources().getColor(info.pressed_txt_color));
                }

                button.setBackgroundResource(info.pressed_drawable);

                //将文本设置成键名
                ((TextView) findViewById(info.txt_id)).setText(HandShankUtil.nameToName.get(HandShankUtil.valueGetKey(okMap, key)));

            } else {
                //如果这个button没被加入okMap，设置成正常的
                Button button = (Button) findViewById(info.id);
                if (info.normal_txt_color != 0) {
                    button.setTextColor(getResources().getColor(info.normal_txt_color));
                }
                button.setBackgroundResource(info.normal_drawable);

            }

        }

    }


    @Override
    protected boolean onKeyEvent(int keyCode, PadKeyEvent event) {
        String deviceName = event.getName();
        if (BlackListManager.getInstance().isInBlackList(deviceName)) return false;

        if (event.getAction() == KeyEvent.ACTION_DOWN) {
//            onKeyDown1(keyCode, padEvent2KeyEvent(event));
        } else {
            onKeyUp1(keyCode, padEvent2KeyEvent(event));
        }

        return super.onKeyEvent(keyCode, event);
    }

    public boolean onKeyUp1(int keyCode, KeyEvent event) {
        String deviceName = event.getDevice().getName();
        if (BlackListManager.getInstance().isInBlackList(deviceName)) return false;
        // TODO Auto-generated method stub

        if (keyCode != KeyEvent.KEYCODE_BACK) {
            //KEY_MAP里没有keycode值，不做处理，如：上下左右键等

            if (!KEY_MAP.containsValue(keyCode)) {
                return true;
            }


            if (keyCode == KeyEvent.KEYCODE_BACK) {
                finish();
                return true;
            }

            //如果有选中的键，进入流程
            if (selectBtn != null) {

                //取出键上的tag值信息
                String tag = (String) selectBtn.getTag();
                //通过点击的keycode，获取keycode的名字
                String keyBoradName = (String) HandShankUtil.valueGetKey(KEY_MAP, keyCode);
                //如果这个keycode名字，在之前已经设过，并存入过map
                if (okMap.containsKey(keyBoradName)) {
                    //取出之前被选中的button的信息类
                    KeyInfo keyInfo = data.get(okMap.get(keyBoradName));
                    //把他的字置空
                    ((TextView) findViewById(keyInfo.txt_id)).setText("");
                }
                //如果这个keycode名字，是被配置文件设置过
                if (GBC_KEY_MAP.containsValue(keyBoradName)) {
                    //取出这个默认设置button的tag值
                    String value = (String) HandShankUtil.valueGetKey(GBC_KEY_MAP, keyBoradName);//Kmap2.get(keyBoradName);

                    //取出这个默认设置button的info
                    KeyInfo info = data.get(value);
                    //把他的描述文字设为空
                    ((TextView) findViewById(info.txt_id)).setText("");
                }
                //存入map中
                okMap.put(keyBoradName, tag);
                isReset = false;
                KeyInfo info = data.get(tag);
                selectBtn.setBackgroundResource(info.pressed_drawable);


                //不再有选中的select
                selectBtn = null;
                //重置所有背景
                revertBtn();


            }

            return true;
        }


        return super.onKeyUp(keyCode, event);
    }

    private class KeyInfo {
        public int id;
        public int normal_drawable;
        public int select_drawable;
        public int pressed_drawable;
        public int normal_txt_color;
        public int select_txt_color;
        public int pressed_txt_color;

        public int txt_id;

        public KeyInfo(int id, int normal_drawable, int select_drawable, int pressed_drawable, int normal_txt_color, int select_txt_color, int pressed_txt_color, int txt_id) {
            this.id = id;
            this.normal_drawable = normal_drawable;
            this.select_drawable = select_drawable;
            this.pressed_drawable = pressed_drawable;
            this.normal_txt_color = normal_txt_color;
            this.select_txt_color = select_txt_color;
            this.pressed_txt_color = pressed_txt_color;
            this.txt_id = txt_id;
        }
    }


    private void initMapData() {

        Map      map      = KeyMapManager.getMap("KEY");
        Set      set      = map.keySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            String name = (String) iterator.next();
            String key  = (String) map.get(name);
            if (HandShankUtil.isAllowSet(name)) {
                KEY_MAP.put(name, Integer.parseInt(key));
            }
        }


        if (KEY_MAP == null || KEY_MAP.size() == 0) {
            KEY_MAP.put(HandShankUtil.KEY_START, 108);
            KEY_MAP.put(HandShankUtil.KEY_SELECT, 109);
            KEY_MAP.put(HandShankUtil.KEY_X, 99);
            KEY_MAP.put(HandShankUtil.KEY_A, 96);
            KEY_MAP.put(HandShankUtil.KEY_Y, 100);
            KEY_MAP.put(HandShankUtil.KEY_B, 97);
            KEY_MAP.put(HandShankUtil.KEY_L1, 102);
            KEY_MAP.put(HandShankUtil.KEY_L2, 104);
            KEY_MAP.put(HandShankUtil.KEY_R1, 103);
            KEY_MAP.put(HandShankUtil.KEY_R2, 105);
            KEY_MAP.put(HandShankUtil.KEY_BUTTON_THUMBR, 107);
        }/*else{
            Map map = KeyMapManager.getMap("KEY");
			Set set = map.keySet();
			Iterator iterator = set.iterator();
			while (iterator.hasNext()){
				String name = (String) iterator.next();
				String key = (String) map.get(name);
				if(HandShankUtil.isAllowSet(name)) {
					KEY_MAP.put(name, Integer.parseInt(key));
				}
			}



		}*/

		/*KEY_MAP.put(HandShankUtil.KEY_START,108);
        KEY_MAP.put(HandShankUtil.KEY_SELECT,109);
		KEY_MAP.put(HandShankUtil.KEY_X,99);
		KEY_MAP.put(HandShankUtil.KEY_A,96);
		KEY_MAP.put(HandShankUtil.KEY_Y,100);
		KEY_MAP.put(HandShankUtil.KEY_B,97);
		KEY_MAP.put(HandShankUtil.KEY_L1,102);
		KEY_MAP.put(HandShankUtil.KEY_L2,104);
		KEY_MAP.put(HandShankUtil.KEY_R1,103);
		KEY_MAP.put(HandShankUtil.KEY_R2,105);
		KEY_MAP.put(HandShankUtil.KEY_BUTTON_THUMBR,107);*/


        GBC_KEY_MAP = getMap();//KeyMapManager.getMap("FC_KEY_MAP");
        if (GBC_KEY_MAP == null || GBC_KEY_MAP.size() == 0) {
            GBC_KEY_MAP.put(HandShankUtil.GBC_KEY_SELECT, HandShankUtil.KEY_SELECT);
            GBC_KEY_MAP.put(HandShankUtil.GBC_KEY_START, HandShankUtil.KEY_START);

            GBC_KEY_MAP.put(HandShankUtil.GBC_KEY_TURBO_A, HandShankUtil.KEY_X);
            GBC_KEY_MAP.put(HandShankUtil.GBC_KEY_A, HandShankUtil.KEY_A);
            GBC_KEY_MAP.put(HandShankUtil.GBC_KEY_TURBO_B, HandShankUtil.KEY_Y);
            GBC_KEY_MAP.put(HandShankUtil.GBC_KEY_B, HandShankUtil.KEY_B);


            GBC_KEY_MAP.put(HandShankUtil.GBC_KEY_AB, HandShankUtil.KEY_R1);

        }


    }


    private void reset() {
        isReset = true;
        okMap.clear();
        okMap.put(HandShankUtil.KEY_SELECT, HandShankUtil.GBC_KEY_SELECT);
        okMap.put(HandShankUtil.KEY_START, HandShankUtil.GBC_KEY_START);
        okMap.put(HandShankUtil.KEY_X, HandShankUtil.GBC_KEY_TURBO_A);
        okMap.put(HandShankUtil.KEY_A, HandShankUtil.GBC_KEY_A);
        okMap.put(HandShankUtil.KEY_Y, HandShankUtil.GBC_KEY_TURBO_B);
        okMap.put(HandShankUtil.KEY_B, HandShankUtil.GBC_KEY_B);
        okMap.put(HandShankUtil.KEY_R1, HandShankUtil.GBC_KEY_AB);


        GBC_KEY_MAP.put(HandShankUtil.GBC_KEY_SELECT, HandShankUtil.KEY_SELECT);
        GBC_KEY_MAP.put(HandShankUtil.GBC_KEY_START, HandShankUtil.KEY_START);

        GBC_KEY_MAP.put(HandShankUtil.GBC_KEY_TURBO_A, HandShankUtil.KEY_X);
        GBC_KEY_MAP.put(HandShankUtil.GBC_KEY_A, HandShankUtil.KEY_A);
        GBC_KEY_MAP.put(HandShankUtil.GBC_KEY_TURBO_B, HandShankUtil.KEY_Y);
        GBC_KEY_MAP.put(HandShankUtil.GBC_KEY_B, HandShankUtil.KEY_B);


        GBC_KEY_MAP.put(HandShankUtil.GBC_KEY_AB, HandShankUtil.KEY_R1);
        Set      set      = GBC_KEY_MAP.keySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            String keyname = (String) iterator.next();
            String value   = GBC_KEY_MAP.get(keyname);

            KeyInfo info = data.get(keyname);

            ((TextView) findViewById(info.txt_id)).setText(HandShankUtil.nameToName.get(value));
            (((Button) findViewById(info.id))).setBackgroundResource(info.normal_drawable);
            if (info.normal_txt_color != 0) {
                (((Button) findViewById(info.id))).setTextColor(getResources().getColor(info.normal_txt_color));
            }

        }


        KeyMapManager.writeToConfigVK(this, KeyMap.EmuMap.GBC, putMap(okMap));
        okMap.clear();


    }

    private void initView() {
        Set      set      = GBC_KEY_MAP.keySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            String keyname = (String) iterator.next();
            String value   = GBC_KEY_MAP.get(keyname);

            KeyInfo info = data.get(keyname);
            ((TextView) findViewById(info.txt_id)).setText(HandShankUtil.nameToName.get(value));
        }
    }

    private Map<String, String> putMap(Map<String, String> okMap) {
        Map<String, String> ret = new HashMap<String, String>();

        Iterator iterator = okMap.keySet().iterator();
        while (iterator.hasNext()) {
            String key   = (String) iterator.next();
            String value = okMap.get(key);

            ret.put(key, HandShankUtil.gbcConvertMap.get(value));

        }


        return ret;
    }

    private Map<String, String> getMap() {
        Map<String, String> ret = new HashMap<String, String>();

        KeyMap.EmuMap       emuMap = KeyMap.EmuMap.GBC;
        Map<String, String> map    = KeyMapManager.getMap(emuMap.section);

        Iterator<Map.Entry<String, String>> iterator = HandShankUtil.gbcConvertMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();

            String key   = entry.getKey();
            String value = entry.getValue();

            String V_KEY = map.get(value);

            ret.put(key, V_KEY);

        }

        return ret;
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {

        super.onPause();
    }

}
